package thread_pool;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/5/23
 * Time:12:05
 * 使用ThreadLocal
 **/
public class PoolDemo23 {
    //创建ThreadLocal
    static ThreadLocal<String > threadLocal = new ThreadLocal<>();
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //set threadLocal

                    //得到名称
                    String tName = Thread.currentThread().getName();
                    //设置名称
                    threadLocal.set(tName);
                    System.out.println(String.format("线程：%s 设置了值：%s", tName, tName));
                    printTName();
                }finally {
                    threadLocal.remove();//一定要执行remove
                }
            }
        },"线程1");
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //set threadLocal
                    String tName = Thread.currentThread().getName();
                    threadLocal.set(tName);
                    System.out.println(String.format("线程：%s 设置了值：%s", tName, tName));
                    printTName();
                }finally {
                    threadLocal.remove();
                }
            }
        },"线程2");
        t2.start();
    }

    //打印tName
    private static void printTName() {
        String tName = Thread.currentThread().getName();
        //得到存放在ThreadLocal中的值
        String result = threadLocal.get();
        System.out.println(String.format("线程：%s 取得：%s",tName,result));

    }
}
